﻿using Common.Log;
using DryWCS.Model.PLCModel;
using Sharp7;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DryWCS.Biz.Util
{
    public class Util
    {
        #region 解析读取的PLC数据
        public static void AnalysisBytes<T>(T t, byte[] bytes)
        {
            string type = null;
            int startPos = 0;
            int bitPos = 0;
            int size = 0;
            int count = 0;
            var plist = new List<PropertyInfo>(typeof(T).GetProperties());
            try
            {
                //type.GetType().GetProperties(). 
                plist.ForEach(p =>
                {
                    count++;
                    object[] objAttrs = p.GetCustomAttributes(typeof(PLCAttribute), true);
                    if (objAttrs.Length > 0)
                    {
                        foreach (var obj in objAttrs)
                        {
                            PLCAttribute atrr = obj as PLCAttribute;
                            type = atrr.Type;
                            startPos = atrr.StartPosition;
                            bitPos = atrr.BitPosition;
                            size = atrr.Size;
                        }
                        switch (type.ToLower())
                        {
                            case "bool":
                                p.SetValue(t, S7.GetBitAt(bytes, startPos, bitPos));
                                break;
                            case "byte":
                                p.SetValue(t, S7.GetByteAt(bytes, startPos));
                                break;
                            case "string":
                                p.SetValue(t, S7.GetStringAt(bytes, startPos));
                                break;
                            case "ushort":
                                p.SetValue(t, (ushort)S7.GetWordAt(bytes, startPos));
                                break;
                            case "int16":
                                p.SetValue(t, (Int16)S7.GetIntAt(bytes, startPos));
                                break;
                            case "int":
                                p.SetValue(t, S7.GetDIntAt(bytes, startPos));
                                break;
                            case "float":
                                p.SetValue(t, S7.GetRealAt(bytes, startPos));
                                break;
                        }
                    }
                });
            
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog($"解析读取的PLC数据时出错{plist[count].Name}", ex);
            }
        }
        #endregion
    }
}
